package com.xzz.finger;

/**
 * @author: hhz
 * @create: 2022-02-18 14:15
 * 剑指 Offer 25. 合并两个排序的链表
 **/
public class MergeTwoLists {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {
        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1,new ListNode(2,new ListNode(4)));
        ListNode list2 = new ListNode(1,new ListNode(3,new ListNode(4)));
        ListNode listNode = mergeTwoLists(list1, list2);
        System.out.println();
    }
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode tail = head;
        ListNode p1 = l1;
        ListNode p2= l2;
        while(p1!=null && p2!=null){
            if(p1.val>p2.val){
                tail.next = p2;
                p2 = p2.next;
            }else {
                tail.next =p1 ;
                p1 = p1.next;
            }
            tail = tail.next;
        }
        if (p1!=null){
            tail.next = p1;
        }
        if (p2!=null){
            tail.next = p2;
        }
        return head.next;
    }
}
